//
//  LXRRecommendViewController.m
//  01- 百思不得姐
//
//  Created by mac on 16/6/8.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRRecommendViewController.h"

#import "LXRRecommendLeftModel.h"
#import "LXRRecommecdLeftCell.h"

#import "LXRRecommendRightCell.h"
#import "LXRRecommendRightModel.h"

#import "LXRHTTPSessionManager.h"
#import "SVProgressHUD.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "MBProgressHUD+MJ.h"

#define LXRLeftModel self.LeftDataArray[self.LeftTableView.indexPathForSelectedRow.row]
@interface LXRRecommendViewController ()<UITableViewDelegate,UITableViewDataSource>
/**左边的类别数据*/
@property(nonatomic,strong)NSArray* LeftDataArray;

/**左边的UITableView类别控件 */
@property (weak, nonatomic) IBOutlet UITableView *LeftTableView;
/**右边用户UITableView类别控件 */
@property (weak, nonatomic) IBOutlet UITableView *RightTableView;
/**请求参数*/
@property(nonatomic,strong)NSMutableDictionary* params;
/**AFN请求管理者*/
@property(nonatomic,strong)LXRHTTPSessionManager* manager;

@end

@implementation LXRRecommendViewController
/**AFN请求管理者懒加载*/
-(AFHTTPSessionManager *)manager{
    
    if (_manager == nil) {
        _manager = [LXRHTTPSessionManager manager];
    }
    return _manager;
}

/**标识*/
static NSString * const LXRCellId = @"left";
static NSString * const LXRRightId = @"right";

- (void)viewDidLoad {
    [super viewDidLoad];
    //控件初始化
    [self setupTableView];
   
    //加载左边数据---->发送请求
    [self LeftGet];
    
    //添加刷新控件
    [self setupRefresh];
}

#pragma mark - 控件初始化
-(void)setupTableView{
    //加载xib 注册
    [self.LeftTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRRecommecdLeftCell class]) bundle:nil] forCellReuseIdentifier:LXRCellId];
    [self.RightTableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRRecommendRightCell class]) bundle:nil] forCellReuseIdentifier:LXRRightId];
    
    //设置Nav标题
    self.title = @"推荐关注";
    //设置背景色
    self.view.backgroundColor = LXR_BJ_Color;
    //设置Inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.LeftTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.RightTableView.contentInset = self.LeftTableView.contentInset;
    self.RightTableView.rowHeight = 70;
    
}

#pragma mark - 添加刷新控件--->上下拉刷新
-(void)setupRefresh{
    self.RightTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    
    self.RightTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
  
}

#pragma mark - 时刻监测footer状态
/**
 * 时刻监测footer状态
 */
-(void)checkFooterState{
    //左边被选中的类别模型
    LXRRecommendLeftModel* left = LXRLeftModel;
    
    //每次刷新右边数据时,都控制footer显示或者隐藏
    self.RightTableView.mj_footer.hidden = (left.Rights.count == 0);
    
    if (left.Rights.count == left.total) { //全部数据已经加载完毕
        [self.RightTableView.mj_footer endRefreshingWithNoMoreData];
    }else{                                 //还没有加载完毕
        [self.RightTableView.mj_footer endRefreshing];
    }
    
}


#pragma mark - 加载左边数据---->发送请求
-(void)LeftGet{

    //显示指示器
    [MBProgressHUD showMessage:@"加载中"];
    //发送请求
    NSMutableDictionary* params = [NSMutableDictionary new];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    
    LXRWeakSelf;
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //服务器返回的JSON数据
        //LXRLog(@"%@",responseObject);
        //隐藏指示器
        [MBProgressHUD hideHUD];
        
        //通过数组responseObject[@"list"]进行转模型LXRRecommendLeftModel到LeftDataArray数组里
        weakSelf.LeftDataArray = [LXRRecommendLeftModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        //刷新数据
        [weakSelf.LeftTableView reloadData];
        
        //设置左边列表cell默认选中首行
        [weakSelf.LeftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        //让用户表格头部进入刷新
        [weakSelf.RightTableView.mj_header beginRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //显示失败信息
        [MBProgressHUD showError:@"加载推荐失败"];
    }];
}

#pragma mark - Header控件---->上拉刷新
-(void)loadNewUsers{
    //获取左边类别模型
    LXRRecommendLeftModel* model = LXRLeftModel;
    
    //设置当前页码为1
    model.currentPage = 1;
    
    //请求参数
    NSMutableDictionary* params = [NSMutableDictionary new];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(model.ID);
    params[@"page"] = @(model.currentPage);
    //储存当前请求参数
    self.params = params;
    
    LXRWeakSelf;
    //发送请求给服务器,加载 右边 数据
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil
           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               
               
               
               //字典数组 ---> 模型数组
               NSArray* users= [LXRRecommendRightModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
               
               //清除所有旧数据 防止重复加载
               [model.Rights removeAllObjects];
               
               //添加到当前类别对应的用户数组中
               [model.Rights addObjectsFromArray:users];
               
               //保存总数
               model.total = [responseObject[@"total"] integerValue];
               
               //当储存的请求参数不等于当前请求参数,直接返回
               if (weakSelf.params != params) return ;
               
               //刷新右边表格
               [weakSelf.RightTableView reloadData];
               
               //结束刷新
               [weakSelf.RightTableView.mj_header endRefreshing];
               
               //让底部控件结束刷新
               [weakSelf checkFooterState];
               
           } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               //提醒
               [MBProgressHUD showError:@"加载用户数据失败"];
               //结束刷新
               [weakSelf.RightTableView.mj_header endRefreshing];
           }];

}

#pragma mark - Footer控件--->下拉加载数据
-(void)loadMoreData{
    
    LXRRecommendLeftModel* model = LXRLeftModel;
    
    //发送请求给服务器,加载右边的数据
    NSMutableDictionary* params = [NSMutableDictionary new];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @([model ID]);
    params[@"page"] = @(++model.currentPage);
    self.params = params;
    
    LXRWeakSelf;
    //发送请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil
           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               
               
               //字典数组 ---> 模型数组
               NSArray* users= [LXRRecommendRightModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
               
               //添加到当前类别对应的用户数组中
               [model.Rights addObjectsFromArray:users];
               
               //当储存的请求参数不等于当前请求参数,直接返回
               if (weakSelf.params != params) return ;
               
               //刷新右边表格
               [weakSelf.RightTableView reloadData];
               
               //让底部控件结束刷新
               [weakSelf checkFooterState];
              
               
           } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               //当储存的请求参数不等于当前请求参数,直接返回
               if (weakSelf.params != params) return ;
               
               //提醒
               [MBProgressHUD showError:@"加载用户数据失败"];
               //让底部控件结束刷新
               [weakSelf.RightTableView.mj_footer endRefreshing];
           }];
    
}



#pragma mark - <UITableViewDataSource>数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //左边的类别表格
    if (tableView == self.LeftTableView) return self.LeftDataArray.count;

    //监测footer的状态
    [self checkFooterState];
    
    //右边的用户表格
    return [LXRLeftModel Rights].count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.LeftTableView) {
        LXRRecommecdLeftCell* cell = [tableView dequeueReusableCellWithIdentifier:LXRCellId];
        cell.model = self.LeftDataArray[indexPath.row];
        return  cell;
    }else{
        LXRRecommendRightCell* cell = [tableView dequeueReusableCellWithIdentifier:LXRRightId];
        
        cell.model = [LXRLeftModel Rights][indexPath.row];
        return cell;
    }
}

#pragma mark - <UITableViewDelegate>代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //结束上一次刷新,当网速慢的时候
    [self.RightTableView.mj_header endRefreshing];
    [self.RightTableView.mj_footer endRefreshing];
    
    LXRRecommendLeftModel* model = self.LeftDataArray[indexPath.row];
    
    if (model.Rights.count) {
        //显示曾经的数据
        [self.RightTableView reloadData];
    }else{
        //赶紧刷新表格,目的是:马上显示当前model的用户数据,不让用户看见上一个model的残留数据
        [self.RightTableView reloadData];
        //进入header控件---->刷新状态
        [self.RightTableView.mj_header beginRefreshing];
    }
}

#pragma mark - 控制器的销毁
-(void)dealloc{
    //停止所有操作
    [self.manager.operationQueue cancelAllOperations];
}
@end
